/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.hsos.samcomm.common.i18n;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

/**
 *
 * @author Dennis
 */
@ManagedBean(name = "language")
@SessionScoped
public class LanguageBean implements Serializable {

    private String selectedCountry;
    private Map<String, Object> countries;
    private I18nFacade i18n = I18nFacade.getInstance();

    @PostConstruct
    void init() {
        Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
        i18n.setCurrentLocal(locale);
        createLanguageMap(locale);
    }

    private void createLanguageMap(Locale locale) {
        countries = new LinkedHashMap<>();

        countries.put(Locale.GERMAN.getDisplayName(locale), Locale.GERMAN);
        countries.put(Locale.ENGLISH.getDisplayName(locale), Locale.ENGLISH);
    }

    //value change event listener
    public void countryLocaleCodeChanged(ValueChangeEvent e) {
        String newLocaleValue = e.getNewValue().toString();

        //loop country map to compare the localeCode code
        for (Map.Entry<String, Object> entry : countries.entrySet()) {
            if (entry.getValue().toString().equals(newLocaleValue)) {
                //FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale)entry.getValue());
                i18n.setCurrentLocal((Locale) entry.getValue());
            }
        }

        createLanguageMap(getCurrentLocale());
    }

    public Locale getCurrentLocale() {
        return i18n.getCurrentLocale();
    }

    public void setCurrentLocale(Locale currentLocale) {
        i18n.setCurrentLocal(currentLocale);
    }

    public Map<String, Object> getCountries() {
        return countries;
    }

    public void setCountries(Map<String, Object> countries) {
        this.countries = countries;
    }

    public String getSelectedCountry() {
        return selectedCountry;
    }

    public void setSelectedCountry(String localeCode) {
        this.selectedCountry = localeCode;
    }
}
